// 请求封装
import { ResultEnum } from '@/config/httpEnum'
import { ErrorPageNameMap } from '@/config/pageEnum'
import { close, start } from '@/plugins/nprogress'
import { redirectErrorPage } from '@/utils'
import axios, {
  type AxiosResponse,
  type InternalAxiosRequestConfig
  // type AxiosRequestConfig
} from 'axios'
import { useCommonStore } from '@/store/common'

let reqNum: number = 0
const commonStore = useCommonStore()

// loading动画
const startLoading = () => {
  if (reqNum === 0) {
    commonStore.setLoading(true)
  }
  reqNum++
}
const endLoading = () => {
  if (reqNum <= 0) return
  reqNum--
  if (reqNum === 0) {
    commonStore.setLoading(false)
  }
}

const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_PATH,
  timeout: ResultEnum.TIMEOUT
})

// 请求拦截
axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    start()
    startLoading()
    return config
  },
  (error: InternalAxiosRequestConfig) => {
    Promise.reject(error)
  }
)

// 响应拦截
axiosInstance.interceptors.response.use(
  (res: AxiosResponse) => {
    close()
    setTimeout(() => {
      endLoading()
    }, 150)
    const { code } = res.data as { code: number }
    if (code === undefined || code === null) return Promise.resolve(res.data)
    if (code === ResultEnum.DATA_SUCCESS) return Promise.resolve(res.data)
    // 重定向
    if (ErrorPageNameMap.get(code)) redirectErrorPage(code)
    return Promise.resolve(res.data)
  },
  (err: AxiosResponse) => {
    close()
    endLoading()
    Promise.reject(err)
  }
)

export default axiosInstance
